package net.ufrog.common.xls.disposer;

import net.ufrog.common.exception.ServiceException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;

import java.math.BigDecimal;

/**
 * 整型解析器
 *
 * @author ultrafrog, ufrog.net@gmail.com
 * @version 0.1, 2017-01-16
 * @since 0.1
 */
public class IntDisposer extends Disposer {

    @Override
    public Object get(Cell cell, net.ufrog.common.xls.annotation.Cell annotation) {
        if (cell.getCellTypeEnum() == CellType.NUMERIC) {
            return new BigDecimal(cell.getNumericCellValue()).intValue();
        } else if (cell.getCellTypeEnum() == CellType.STRING) {
            return new BigDecimal(cell.getStringCellValue()).intValue();
        } else if (cell.getCellTypeEnum() == CellType.BLANK) {
            return null;
        } else {
            throw new ServiceException("cannot parse cell '" + cell.getCellTypeEnum() + "' value to BigDecimal.");
        }
    }

    @Override
    public void set(Cell cell, Object value, net.ufrog.common.xls.annotation.Cell annotation) {
        cell.setCellType(CellType.NUMERIC);
        if (value instanceof Number) {
            cell.setCellValue(((Number) value).intValue());
        } else if (value instanceof String) {
            cell.setCellValue(new BigDecimal((String) value).doubleValue());
        } else {
            throw new ServiceException("cannot set cell value by type " + value.getClass().getName() + ".");
        }
    }
}
